from mcp import StdioServerParameters, ClientSession
from mcp.client.stdio import stdio_client
from langchain_mcp_adapters.tools import load_mcp_tools
import asyncio
from langchain.agents import initialize_agent, AgentType
from langchain_openai import ChatOpenAI
from pydantic import SecretStr

# 创建模型实例（远程调用）
llm = ChatOpenAI(
    model_name="qwen3-max",
    temperature=0,
    openai_api_key=SecretStr("sk-f4fb03bbc29b4f0995b60dec52645af0"),
    openai_api_base="https://dashscope.aliyuncs.com/compatible-mode/v1",
    streaming=True,
)

async def create_mcp_stdio_client():
    # 相当于使用python运行 mcp_stdio_server.py 启动 stdio 本地服务器
    server_params = StdioServerParameters(
        command="python",
        args=[r"app\mcp\stdio\mcp_stdio_server.py"]
    )

    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()

            tools = await load_mcp_tools(session)
            
            agent = initialize_agent(
                tools,
                llm,
                agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
                verbose=True
            )

            resp = await agent.arun("请计算30加上15乘以20的结果是多少？")
            return resp

asyncio.run(create_mcp_stdio_client())